package rpc.registry.zookeeper;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import rpc.enums.RpcErrorMessageEnum;
import rpc.exceprion.RpcException;
import rpc.extension.ExtensionLoader;
import rpc.loadbalance.LoadBalance;
import rpc.registry.ServiceDiscovery;
import rpc.registry.zookeeper.utils.CuratorUtils;
import rpc.remote.dto.RpcRequest;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @ClassName: ZkServiceDiscoveryImpl
 * @Description: 在Zookeeper中查找服务
 * @author: Kowk
 * @since:1.0.0
 */
@Slf4j
public class ZkServiceDiscoveryImpl implements ServiceDiscovery {

    private final LoadBalance loadBalance;

    public ZkServiceDiscoveryImpl() {
        this.loadBalance = (LoadBalance) ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension("loadBalance");
    }

    @Override
    public InetSocketAddress lookupService(RpcRequest request) {
        String rpcServiceName = request.getRpcServiceName();
        CuratorFramework zkClient = CuratorUtils.getZkClient();
        List<String> serviceUrlList = CuratorUtils.getChildrenNodes(zkClient, rpcServiceName);
        if (serviceUrlList == null || serviceUrlList.size() == 0) {
            throw new RpcException(RpcErrorMessageEnum.SERVICE_CAN_NOT_BE_FOUND, rpcServiceName);
        }
        //负载均衡
        String targetServiceUrl = loadBalance.selectServiceAddress(serviceUrlList,request);
        log.info("成功找到服务地址:[{}]",targetServiceUrl);
        String[] socketAddressArray = targetServiceUrl.split(":");
        String host = socketAddressArray[0];
        int port = Integer.parseInt(socketAddressArray[1]);
        return new InetSocketAddress(host,port);
    }
}
